package com.learn.ssm.handler;

import com.github.pagehelper.PageInfo;
import com.learn.ssm.entity.Emp;
import com.learn.ssm.service.api.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class EmpHandler {

    @Autowired
    private EmpService empService;


    @RequestMapping("/get/all")
    public String getAll(Model model) {
        List<Emp> empList = empService.selectAll();
        model.addAttribute("empList", empList);
        return "emp-list";
    }

    @RequestMapping("/get/page/{pageNo}")
    public String getPage(@PathVariable("pageNo") Integer pageNo, Model model) {
        // pageInfo 对象封装了和分页相关的所有信息
        PageInfo<Emp> pageInfo = empService.getPageInfo(pageNo);

        model.addAttribute("pageInfo", pageInfo);

        return "emp-page";
    }

    @DeleteMapping("/emp/{empId}/{pageNo}")
    public String doRemove(@PathVariable Integer empId, @PathVariable Integer pageNo) {
        empService.removeByEmpId(empId);
        return "redirect:/get/page/" + pageNo;
    }

    @GetMapping("/emp/{empId}/{pageNo}")
    public String editEmp(Model model,
                          @PathVariable Integer empId,
                          @PathVariable Integer pageNo) {

        Emp emp = empService.getEmpById(empId);
        model.addAttribute("emp", emp);
        model.addAttribute("pageNo", pageNo);
        return "emp-edit-form";
    }

    @PutMapping("/emp")
    public String updateEmp(@RequestParam("pageNo") Integer pageNo,
                            Emp emp) {

        empService.updateEmp(emp);
        return "redirect:/get/page/" + pageNo;
    }

    @PostMapping("/emp")
    public String saveEmp(Emp emp) {
        empService.saveEmp(emp);
        return "redirect:/get/page/" + Integer.MAX_VALUE;
    }

}
